if (!window) {
    throw "无法访问DOM对象。";
}
if (typeof jQuery === "undefined" && typeof $ === "undefined") {
    throw "缺少JQuery组件。(sharp.js需要在jquery之后载入)";
}
if (!(typeof bootstrap.Modal === 'function')) {
    throw "缺少bootStrap组件。";
}
document.onreadystatechange = function (e) {
    if (document.readyState === "interactive") {
        console.log("页面DOM已解析，可进行交互。");
    }
    else if (document.readyState === "complete") {
        console.log("页面资源已加载完成。");
    }
};
String.prototype["startWith"] = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
};
String.prototype["endWith"] = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
};
String.prototype["Format"] = String.prototype["format"] = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length === 1 && typeof args === "object") {
            for (var key in args) {
                if (args[key] !== undefined) {
                    var regexp = new RegExp("({" + key + "})", "g");
                    var value = args[key];
                    if (value === null) {
                        value = "";
                    }
                    result = result.replace(regexp, value);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] !== undefined) {
                    var reg_exp = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg_exp, arguments[i]);
                }
            }
        }
    }
    return result;
};
Date.prototype["Format"] = Date.prototype["Format"] = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
var WebApiResult = (function () {
    function WebApiResult(jqxhr) {
        var me = this;
        jqxhr.done(function (result) {
            me.status = result.status;
            me.message = result.message;
            me.data = result.data;
            if (result.status === 1) {
                me.call_done(me);
            }
            else {
                me.call_fail(me);
            }
        });
        jqxhr.fail(function (xhr) {
            me.status = -xhr.status;
            me.message = xhr.responseText;
            if (!me.message) {
                if (me.status == 0) {
                    me.message = "网络异常。";
                }
                else if (me.status == -404) {
                    me.message = "请求的目标不存在。";
                }
            }
            me.data = null;
            me.call_fail(me);
        });
        jqxhr.always(function () {
            me.call_always(me);
        });
    }
    WebApiResult.prototype.call_done = function (result) {
        if (this._done) {
            try {
                this._done.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.call_fail = function (result) {
        if (this._fail) {
            try {
                this._fail.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.call_always = function (result) {
        if (this._always) {
            try {
                this._always.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.done = function (callback) {
        if (!this._done) {
            this._done = new Array();
        }
        this._done.push(callback);
        return this;
    };
    WebApiResult.prototype.fail = function (callback) {
        if (!this._fail) {
            this._fail = new Array();
        }
        this._fail.push(callback);
        return this;
    };
    WebApiResult.prototype.always = function (callback) {
        if (!this._always) {
            this._always = new Array();
        }
        this._always.push(callback);
        return this;
    };
    return WebApiResult;
}());
var HtmlUtil = (function () {
    function HtmlUtil() {
    }
    HtmlUtil.htmlEncode = function (str) {
        var s = "";
        if (!str || str.length === 0)
            return "";
        s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        return s;
    };
    HtmlUtil.htmlDecode = function (str) {
        var s = "";
        if (!str || str.length === 0)
            return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        return s;
    };
    return HtmlUtil;
}());
var Guid = (function () {
    function Guid(guid) {
        var _this = this;
        this.equals = function (other) { return Guid.isGuid(other) && _this.value.toUpperCase() === other.toString().toUpperCase(); };
        this.isEmpty = function () { return _this.value === Guid.globals.guidDefaultValue; };
        this.toString = function () { return _this.value; };
        if (!guid)
            throw new TypeError('Invalid argument; `value` has no value.');
        this.value = Guid.globals.guidDefaultValue;
        if (guid && Guid.isGuid(guid))
            this.value = guid;
    }
    Guid.gen = function (count) {
        if (count === void 0) { count = 1; }
        var out = '';
        for (var i = 0; i < count; i++)
            out += ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
        return out;
    };
    Guid.NewGuid = function () {
        return Guid.create();
    };
    Guid.prototype.toJSON = function () { return { value: this.value }; };
    var _a;
    _a = Guid;
    Guid.globals = {
        guidDefaultValue: '00000000-0000-0000-0000-000000000000',
        validationPattern: '^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$'
    };
    Guid.validator = new RegExp(_a.globals.validationPattern, 'i');
    Guid.isGuid = function (guid) { return guid && (guid instanceof Guid || Guid.validator.test(guid.toString())); };
    Guid.create = function () { return new Guid([Guid.gen(2), Guid.gen(), Guid.gen(), Guid.gen(), Guid.gen(3)].join('-')); };
    Guid.createEmpty = function () { return new Guid(Guid.globals.guidDefaultValue); };
    Guid.parse = function (guid) { return new Guid(guid); };
    Guid.raw = function () { return [Guid.gen(2), Guid.gen(), Guid.gen(), Guid.gen(), Guid.gen(3)].join('-'); };
    Guid.EMPTY = Guid.parse(Guid.globals.guidDefaultValue);
    return Guid;
}());
var WindowHelper = (function () {
    function WindowHelper() {
    }
    WindowHelper.isType = function (obj, typeName) {
        return Object.prototype.toString.call(obj) === '[object ' + typeName + ']';
    };
    WindowHelper.formDataToJson = function (formData) {
        var objData = {};
        formData.forEach(function (v, k, f) {
            objData[k] = v;
        });
        return objData;
    };
    ;
    WindowHelper.findParent = function (ele, selector, endele) {
        var jq = $(ele);
        if (jq.is(selector)) {
            return ele;
        }
        var ps = $(ele).parents();
        for (var i in ps) {
            var p = ps[i];
            if ($(p).is(selector)) {
                return p;
            }
            if (p === endele) {
                return null;
            }
        }
        return null;
    };
    return WindowHelper;
}());
var API = (function () {
    function API() {
    }
    API.apiPostJson = function (url, data) {
        var jqxhr = $.ajax({
            url: url,
            async: true,
            method: 'POST',
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json;charset=UTF-8",
            processData: false,
            cache: false,
            success: function (data) {
            },
            error: function (jqXHR) {
                console.log(JSON.stringify(jqXHR));
            }
        });
        return new WebApiResult(jqxhr);
    };
    ;
    API.apiPostText = function (url, data) {
        var jqxhr = $.ajax({
            url: url,
            async: true,
            method: 'POST',
            data: JSON.stringify(data),
            dataType: "text",
            contentType: "text/plain;charset=UTF-8",
            processData: false,
            cache: false,
            success: function (data) {
            },
            error: function (jqXHR) {
                console.log(JSON.stringify(jqXHR));
            }
        });
        return new WebApiResult(jqxhr);
    };
    API.apiPostForm = function (url, data, upProgress, downProgress) {
        if (!WindowHelper.isType(data, "FormData")) {
            var fd = new FormData();
            for (var k in data) {
                fd.append(k, data[k]);
            }
            data = fd;
        }
        var jqxhr = $.ajax({
            url: url,
            async: true,
            method: 'POST',
            data: data,
            dataType: "json",
            contentType: false,
            processData: false,
            cache: false,
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.upload.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (upProgress) {
                            upProgress(evt.loaded, evt.total);
                        }
                    }
                };
                xhr.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (downProgress) {
                            downProgress(evt.loaded, evt.total);
                        }
                    }
                };
                return xhr;
            }
        });
        return new WebApiResult(jqxhr);
    };
    API.apiGet = function (url, paras, downProgress) {
        var jqxhr = $.ajax({
            url: url,
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            type: 'GET',
            async: true,
            data: paras,
            dataType: 'json',
            cache: false,
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (downProgress) {
                            downProgress(evt.loaded, evt.total);
                        }
                    }
                };
                return xhr;
            }
        });
        return new WebApiResult(jqxhr);
    };
    API.httpGet = function (url, paras, downProgress) {
        return $.ajax({
            url: url,
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            type: 'GET',
            async: true,
            data: paras,
            dataType: 'text',
            cache: false,
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (downProgress) {
                            downProgress(evt.loaded, evt.total);
                        }
                    }
                };
                return xhr;
            }
        });
    };
    return API;
}());
var Dialog = (function () {
    function Dialog() {
    }
    Dialog.dlgSuccess = function (content, title, onHideHandler) {
        if (!title) {
            title = "";
        }
        if (!content) {
            content = "";
        }
        var str = '<div class="modal fade" tabindex="-1" data-bs-backdrop="static" role="dialog" aria-hidden="true">' +
            '<div class="modal-dialog modal-dialog-centered" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title" style="color:green"><i class="fa fa-check-circle"></i>' + title + '</h5>' +
            '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">' +
            '</button>' +
            '</div>' +
            '<div class="modal-body alert-success">' + content +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var dlg = $(str);
        dlg.on("hidden.bs.modal", onHideHandler);
        dlg.modal("show");
        return dlg;
    };
    ;
    Dialog.dlgInfo = function (content, title, onHideHandler) {
        if (!title) {
            title = "";
        }
        if (!content) {
            content = "";
        }
        var str = '<div class="modal fade" tabindex="-1" data-bs-backdrop="static" role="dialog" aria-hidden="true">' +
            '<div class="modal-dialog modal-dialog-centered" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title"><i class="fa fa-check-circle"></i>' + title + '</h5>' +
            '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">' +
            '</button>' +
            '</div>' +
            '<div class="modal-body alert-info">' + content +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var dlg = $(str);
        dlg.on("hidden.bs.modal", onHideHandler);
        dlg.modal("show");
        return dlg;
    };
    ;
    Dialog.dlgError = function (content, title, onHideHandler) {
        if (!title) {
            title = "";
        }
        if (!content) {
            content = "";
        }
        var str = '<div class="modal fade" tabindex="-1" data-bs-backdrop="static" role="dialog" aria-hidden="true">' +
            '<div class="modal-dialog modal-dialog-centered" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title"><i class="fa fa-exclamation-circle"></i>' + title + '</h5>' +
            '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">' +
            '</button>' +
            '</div>' +
            '<div class="modal-body alert-danger">' + content +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-danger" data-bs-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var dlg = $(str);
        dlg.on("hidden.bs.modal", onHideHandler);
        dlg.modal("show");
        return dlg;
    };
    ;
    Dialog.dlg = function (title, content, btns, btnclickcallback) {
        var btnstr = "";
        var withclose = false;
        if (!btns) {
            btns = ["ok"];
        }
        if ($.inArray('ok', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-primary" data-btntype="ok">确认</button>';
        }
        if ($.inArray('cancel', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-default" data-bs-dismiss="modal" data-btntype="cancel">取消</button>';
        }
        if ($.inArray('yes', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-primary" data-btntype="yes">是</button>';
        }
        if ($.inArray('no', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-default" data-bs-dismiss="modal" data-btntype="no">否</button>';
        }
        if ($.inArray('close', btns) >= 0) {
            withclose = true;
        }
        var gid = Guid.NewGuid().toString();
        var template = ('<div class="modal fade" data-bs-backdrop="static" id="' + gid + '" tabindex="-1" role="dialog">'
            + '<div class="modal-dialog modal-dialog-centered" role="document">'
            + '<div class="modal-content">'
            + '<div class="modal-header">'
            + '<h4 class="modal-title">{0}</h4>'
            + (withclose ? '<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" data-btntype="close"><span aria-hidden="true">&times;</span></button>' : '')
            + '</div>'
            + '<div class="modal-body">'
            + '{1}'
            + '</div>'
            + '<div class="modal-footer">'
            + '{2}'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>').format(title, content, btnstr);
        var dialog = $(template);
        dialog.find("button[data-btntype]").on("click", function (event) {
            if (btnclickcallback) {
                var res = btnclickcallback($(this).data("btntype"), dialog, event);
                if (!res) {
                    dialog.modal("hide");
                }
            }
        });
        dialog.on("hidden.bs.modal", function () {
            dialog.modal("dispose");
            dialog.remove();
        });
        dialog.modal("show");
        return dialog;
    };
    ;
    Dialog.input = function (title, defValue, onresult) {
        var gid = Guid.NewGuid().toString();
        var tid = "input_".concat(gid);
        return Dialog.dlg(title, "<input type=\"text\" id=\"".concat(tid, "\" class=\"form-control\" value=\"").concat(HtmlUtil.htmlEncode(defValue), "\"/>"), ["ok", "cancel"], function (btn, dialog, e) {
            if (btn == "ok") {
                onresult($("#" + tid).val());
            }
            return false;
        });
    };
    ;
    Dialog.toast = function (title1, title2, content, delay, closeCallback) {
        var container = $("body>.toast-container.position-fixed");
        if (container.length == 0) {
            container = $("<div class=\"toast-container position-fixed top-0 start-50 translate-middle-x\" style=\"left:0;top:0;bottom:0;right:0;z-index:20;\"></div>");
            $("body").append(container);
        }
        var dom = "<div class=\"toast\" role=\"alert\" aria-live=\"assertive\" aria-atomic=\"true\">\n    <div class=\"toast-header\"> \n        <strong class=\"me-auto\">".concat(title1, "</strong>\n        <small class=\"text-muted\">").concat(title2, "</small>\n        <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"toast\" aria-label=\"Close\"></button>\n    </div>\n    <div class=\"toast-body\">\n").concat(content, "\n    </div>\n</div>");
        var node = $(dom);
        container.append(node);
        if (delay) {
            node.data("bs-delay", delay);
        }
        var t = bootstrap.Toast.getOrCreateInstance(node[0]);
        t.show();
        node[0].addEventListener('hidden.bs.toast', function () {
            t.dispose();
            node.remove();
            if (container.find(">*").length == 0) {
                container.remove();
            }
            if (closeCallback) {
                closeCallback();
            }
        });
        return t;
    };
    ;
    return Dialog;
}());
Window.prototype["findParent"] = WindowHelper.findParent;
Window.prototype["isType"] = WindowHelper.isType;
Window.prototype["formDataToJson"] = WindowHelper.formDataToJson;
Window.prototype["apiPostText"] = API.apiPostText;
Window.prototype["apiPostJson"] = API.apiPostJson;
Window.prototype["apiPostForm"] = API.apiPostForm;
Window.prototype["apiGet"] = API.apiGet;
Window.prototype["httpGet"] = API.httpGet;
Window.prototype["dlgSuccess"] = Dialog.dlgSuccess;
Window.prototype["dlgError"] = Dialog.dlgError;
Window.prototype["dlg"] = Dialog.dlg;
Window.prototype["input"] = Dialog.input;
Window.prototype["toast"] = Dialog.toast;
(function () {
    $.extend($.fn, {
        mask: function (content, maskDivClass) {
            this.unMask();
            var op = {
                opacity: 0.6,
                z: 19,
                bgcolor: 'rgba(0,0,0,0.5)'
            };
            var original = $(this);
            original.css("position", "relative");
            var position = { top: 0, left: 0 };
            var maskDiv = $('<div class="maskdivgen" style="display:flex;justify-content: center;align-items: center;cursor:wait;"></div>');
            maskDiv.appendTo(original);
            maskDiv.css({
                position: 'absolute',
                top: position.top,
                left: position.left,
                'z-index': op.z,
                width: "100%",
                height: "100%",
                'background-color': op.bgcolor,
                opacity: 0
            });
            if (maskDivClass) {
                maskDiv.addClass(maskDivClass);
            }
            if (content) {
                var msgDiv = $("<div>".concat(content, "</div>"));
                msgDiv.appendTo(maskDiv);
                var widthspace = maskDiv.width() - msgDiv.width();
                var heightspace = maskDiv.height() - msgDiv.height();
                msgDiv.css({
                    top: heightspace / 2 - 2,
                    left: widthspace / 2 - 2
                });
            }
            maskDiv.fadeIn('fast', function () {
                $(this).fadeTo('slow', op.opacity);
            });
            return maskDiv;
        },
        unMask: function () {
            var original = $(document.body);
            if (this[0] && this[0] !== window.document) {
                original = $(this[0]);
            }
            original.find("> div.maskdivgen").fadeOut('slow', function () {
                $(this).remove();
            });
        },
        busy: function (msg) {
            var tag = $(this);
            tag.mask("<div class=\"spinner-border text-primary\" style=\"display:block;margin:auto;\" role=\"status\">\n<span class=\"visually-hidden\">Loading...</span></div>\n<div style=\"color:white;\">".concat(msg ? msg : "", "</div>"));
        },
        unBusy: function () {
            var tag = $(this);
            tag.unMask();
        }
    });
})();
(function (jq) {
    jq.fn.extend({
        apiPostForm: function (upProgress, downProgress) {
            var form = $(this);
            var url = form.attr("action");
            var formData = new FormData(form[0]);
            return API.apiPostForm(url, formData, upProgress, downProgress);
        },
        resetForm: function () {
            var form = $(this);
            form[0].reset();
        },
        setForm: function (data) {
            var form = $(this);
            if (!data) {
                form.resetForm();
                return;
            }
            else {
                for (var i in data) {
                    var tag = form.find("[name='" + i + "']");
                    if (tag.length > 0) {
                        var tagname = tag[0].tagName.toLowerCase();
                        if (tagname === "input") {
                            if (tag.attr("type") === "radio") {
                                form.find("[name='" + i + "'][value='" + data[i] + "']").attr("checked", "checked");
                            }
                            else if (tag.attr("type") === "checkbox") {
                                form.find("[name='" + i + "'][value='true']").attr("checked", data[i]);
                            }
                            else {
                                tag.val(data[i]);
                            }
                        }
                        else if (tagname === "select") {
                            tag.find("option[value='" + data[i] + "']").attr("selected", "selected");
                        }
                        else {
                            tag.text(data[i]);
                        }
                    }
                }
            }
        },
        getFormDataAsJson: function () {
            var form = $(this);
            var formData = new FormData(form[0]);
            return WindowHelper.formDataToJson(formData);
        },
        onSubmitForm: function (onresult, validFunc, upProgress, downProgress) {
            var form = $(this);
            form.on("submit", function () {
                var formData = new FormData(form[0]);
                $("form").addClass('was-validated');
                if (!(form[0].checkValidity()) || (validFunc && !validFunc(formData))) {
                    return false;
                }
                var apiresult = form.postForm(upProgress, downProgress);
                if (onresult) {
                    onresult(apiresult);
                }
                return false;
            });
        }
    });
})(jQuery || $);
